package cn.ccew.sys.web.source;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONSerializer;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.ccew.sys.model.SysOperating;
import cn.ccew.sys.model.SysOrgnization;
import cn.ccew.sys.model.SysResources;
import cn.ccew.sys.web.SysBaseController;

/**
 * s
 * 
 * @author lxj
 * 
 */
@Controller
public class SourceController extends SysBaseController {

	/**
	 * 
	 * @param rootMenuCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("source_load.wb")
	public void loadMenu(String rootMenuCode, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Criteria criteria = this.createCriteria(SysResources.class);

		if (StringUtils.isEmpty(rootMenuCode)) {
			criteria.add(Restrictions.isNull("parent"));
		} else if (rootMenuCode.equals("-1")) {
			criteria.add(Restrictions.isNull("parent"));
		} else {
			criteria.add(Restrictions.eq("parent.id", rootMenuCode));
		}

		criteria.addOrder(Order.desc("priority"));
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

		List<SysResources> list = criteria.list();
		List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();

		for (SysResources temp : list) {
			mapList.add(getMapObj(temp));
		}
		String listJson = JSONSerializer.toJSON(mapList).toString();
		writerTo(response, listJson);
	}

	/**
	 * 加载一条记录，用于显示修改
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("source_loadNodeInfo.wb")
	public void organization_loadOrganization(String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
		SysResources org = baseService.findById(id, SysResources.class);
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("id", org.getId());
		map.put("rsname", org.getRsName());
		map.put("priority", org.getPriority());
		map.put("resfunctionname", org.getRsFunctionName());
		map.put("resfunctionjspath", org.getRsFunctionJsPath());
		responseListJSON(response, map);
	}
	/**
	 * 分页加载
	 * 
	 * @param rootMenuCode
	 * @param start
	 * @param limit
	 * @throws Exception
	 */
	@RequestMapping("source_loadSourceList.wb")
	public void loadSourceList(String rootMenuCode, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		Criteria criteria = this.createCriteria(SysResources.class);

		//criteria.createAlias("parent", "p");

		if (StringUtils.isEmpty(rootMenuCode)) {
			criteria.add(Restrictions.isNull("parent"));
		} else if (rootMenuCode.equals("-1")) {
			criteria.add(Restrictions.isNull("parent"));
		} else {
			criteria.add(Restrictions.eq("parent.id", rootMenuCode));
		}
		criteria.addOrder(Order.desc("priority"));

		String[] excludes = new String[] { "operatings", "children", "parent",
				"roles", "createTime", "lastModifyTime", "priority" };

		responseListJSON(criteria, request, response, excludes);
	}

	/**
	 * 分页加载资源操作列表
	 * 
	 * @param rootMenuCode
	 * @param start
	 * @param limit
	 * @throws Exception
	 */
	@RequestMapping("source_loadSourceOperatingList.wb")
	public void loadSourceListOperating(String sid, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Criteria criteria = this.createCriteria(SysOperating.class);
		if (StringUtils.isEmpty(sid)) {
			criteria.add(Restrictions.eq("resources.id", sid));
		}
		String[] excludes = new String[] { "resources", "children", "parent",
				"roles", "createTime", "lastModifyTime", "priority" };
		responseListJSON(criteria, request, response, excludes);
	}

	/**
	 * 加载一条记录，用于显示修改
	 * 
	 * @param id
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("source_loadSource.wb")
	public void loadSource(String id, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SysResources source = baseService.findById(id, SysResources.class);
		Map<Object, Object> map = new HashMap<Object, Object>();
		map.put("id", source.getId());
		map.put("rsName", source.getRsName());
		map.put("priority", source.getPriority());
		map.put("rsFunctionName", source.getRsFunctionName());
		map.put("rsFunctionJsPath", source.getRsFunctionJsPath());
		String pid = "";
		if (null != source.getParent()) {
			pid = source.getParent().getId();
		}
		map.put("pid", pid);
		responseListJSON(response, map);
	}

	/**
	 * 修改一条记录 id存在为修改，否则创建
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("source_saveSource.wb")
	public void saveSource(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {

			SysResources source = null;
			if (isParameterExist(request, "id")) {
				String id = request.getParameter("id");
				if (StringUtils.isNotEmpty(id)) {
					source = baseService.findById(id, SysResources.class);
				}
			}

			if (null == source) {
				source = new SysResources();
			}

			if (isParameterExist(request, "pid")) {
				SysResources parent = baseService.findById(
						request.getParameter("pid"), SysResources.class);
				source.setParent(parent);
			}

			source.setRsName(request.getParameter("rsName"));
			source.setRsFunctionName(request.getParameter("rsFunctionName"));
			source.setRsFunctionJsPath(request.getParameter("rsFunctionJsPath"));

			baseService.saveOrUpdate(source);
			writerSuccess(response, "保存成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			writerFailure(response, "保存失败");
			e.printStackTrace();
		}

	}
	
	/**
	 * 修改一条记录 id存在为修改，否则创建
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("source_UpdateSource.wb")
	public void updateSource(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			SysResources source = null;
			if (isParameterExist(request, "updateSourceid")) {
				String id = request.getParameter("updateSourceid");
				if (StringUtils.isNotEmpty(id)) {
					source = baseService.findById(id, SysResources.class);
				}
			}
			
			if (null == source) {
				writerFailure(response, "保存失败");
			}else {
				try {
					source.setPriority(new Integer(request.getParameter("updateinfo_px")));
					source.setRsName(request.getParameter("updateinfo_title"));
					source.setRsFunctionName(request.getParameter("updateinfo_function"));
					source.setRsFunctionJsPath(request.getParameter("updateinfo_jspath"));
					baseService.saveOrUpdate(source);
					writerSuccess(response, "保存成功");
				} catch (Exception e) {
					writerFailure(response, "保存失败");
				}
			}
		} catch (Exception e) {
			writerFailure(response, "保存失败");
			e.printStackTrace();
		}

	}

	/**
	 * 删除
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("source_removeSource.wb")
	public void removeSource(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		SysResources source = null;
		if (isParameterExist(request, "id")) {
			String id = request.getParameter("id");
			if (StringUtils.isNotEmpty(id)) {
				source = baseService.findById(id, SysResources.class);
			}
		}
		if (null == source) {
			writerFailure(response, "删除失败，没有找个记录");
			return;
		}
		if (source.getChildren().size() > 0) {
			writerFailure(response, "删除除失败，先删除下级目录");
			return;
		}
		try {
			baseService.delete(source.getId(), SysResources.class);
			writerSuccess(response, "删除成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			writerFailure(response, "删除失败，未知原因");
		}

	}

	/**
	 * 把资源 对象封装成菜单对象
	 * 
	 * @param source
	 * @return
	 */
	private static Map<String, Object> getMapObj(SysResources source) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("id", source.getId());
		map.put("text", source.getRsName());
		map.put("leaf", source.getLeaf());
		map.put("priority", source.getPriority());
		map.put("rsCustomMark", source.getRsCustomMark());
		map.put("functionName", source.getRsFunctionName());
		map.put("rsFunctionJsPath", source.getRsFunctionJsPath());
		return map;
	}

}
